<div class="modal fade" id="register_modal" role="dialog">
    <div class="modal-dialog" style="width:450px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h2 class="modal-title" id="myModalLabel">Register</h2>
            </div>
            <div class="modal-body" id="id_registration_form">
                <form enctype="multipart/form-data" name="register_form" id="register_form">
                {% for field in form %}
                    <div class="row">
                        <div class="form-group">
                            <div class="fieldWrapper">
                                <label class="col-sm-3 control-label">
                                    {{ field.label }}
                                </label>
                                <div class="col-sm-9">
                                    {{ field }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <br/>
                {% endfor %}
                </form>
                <div id="error_box" name="error_box" class="alert alert-danger alert-dismissable" hidden="true">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    ERROR: This is to be filled in by the "print_error" function. If you see this message that means there's an error with your javascript somewhere.
                </div>
            </div>
            <div class="modal-footer">
                <button type="button"
                       class="btn btn-primary"
                        form="register_form"
                     onclick="ajax_register();">
                    <i class="fa fa-check"></i> Register
                </button>
            </div>
        </div>
    </div>
<!-- end modal -->

<script>
    /**
     * When the 'Enter' key is pressed, lets try login in.
     */
    $(document).bind("keypress.13", function(event) {
        if ($('#register_modal').is(':visible')) {
            if (event.which == 13) {
                ajax_register();
            }
        }
    });
                 
    //
    // IMPORTANT:
    //  The following block of code will run when finished running this modal.
    //  Please put all jQuery unbinding code here.
    //
    // When this model hides, we will clear the contents of it.
    $('#register_modal').on('hidden.bs.modal', function (e) {
        $(document).unbind("keypress.key13");
        $('#register_modal').remove();
        $('#ajax_response_register').html('');
    });
    
    /**
     *  Function will call AJAX function to load the register.
     */
    function ajax_register()
    {
        // Only fetch the information on the register modal.
        var $form = $('#register_form');
        
        // Send registration AJAX call to the server.
        var url = 'register';
        $.ajax( url, {
            data: {
               'first_name': $form.find('input[name="first_name"]').val(),
               'last_name': $form.find('input[name="last_name"]').val(),
               'email': $form.find('input[name="email"]').val(),
               'password': $form.find('input[name="password"]').val(),
               'password_repeated': $form.find('input[name="password_repeated"]').val(),
               'is_18_or_plus': $('#id_is_18_or_plus').is(':checked'),
               'captcha_0': $form.find('input[name="captcha_0"]').val(),
               'captcha_1': $form.find('input[name="captcha_1"]').val(),
               'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            type: 'POST',
            success: function(json_result) {
               // success code execution here
               if (json_result.status == "success")
               {
                    // Send the username & password now that it's in the
                    // registery and then login.
                    ajax_authenticate(
                        $form.find('input[name="email"]').val(),
                        $form.find('input[name="password"]').val()
                    );
               }
               else
               {
                    refresh_captcha();
               
                    // Make the hidden error box appear and display error.
                    print_error(json_result.message);
               }
            },
            error: function(xhr,status,error) {
               // error code here
               refresh_captcha();
            },
            complete: function(xhr,status) {
               // completion code here
            }
        });
    }

    /**
     *  Function will call AJAX function to load the register.
     */
    function ajax_authenticate(username, password)
    {
        var url = 'login';
    
        $.ajax( url, {
            data: {
               'username': username,
               'password': password,
               'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            type: 'post',
            success: function(json_result) {
               // success code execution here
               if (json_result.status == "success")
               {
                    $('#register_modal').modal('hide');
               
                    // Load up the course list.
                    window.location = 'courses';
               }
               else
               {
                    alert(json_result.message);
               }
            },
            error: function(xhr,status,error) {
               // error code here
            },
            complete: function(xhr,status) {
               // completion code here
            }
        });
    }

    /**
     * Prints a error box with the contents of the errors received from the server.
     */
    function print_error(json_result)
    {
        $('#error_box').prop("hidden", false); // Display error box.
        
        // Iterate through the JSON array of arrays and generate an error string.
        var message = "<b>Error(s):</b><hr/>";
        var data = $.parseJSON(json_result)
        for (var key in data) {
            if (data.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
                message += "<p>" + key + ": " + data[key] + "<p>";
            }
        }
        
        // Replace the error string with the contents of the error box.
        $('#error_box').html(message);
    }

  /**
   * The following function will cause the captcha to refresh.
   */
  function refresh_captcha()
  {
      var url = location.protocol + "//" + window.location.hostname + ":"
      + location.port + "/captcha/refresh/";
      
      // Make the AJAX-call
      $.getJSON(url, {}, function(json) {
                //var $form = $('modal-body').parents('register_form');
                var $form = $('#register_form');
                $form.find('input[name="captcha_0"]').val(json.key);
                $form.find('img.captcha').attr('src', json.image_url);
        });
                
        return false;
  }

    // Add refresh button after field (this can be done in the template as well)
    $('img.captcha').after(
        $('<a href="#void" class="captcha-refresh">Refresh</a>')
    );
                       
    // Click-handler for the refresh-link
    $('.captcha-refresh').click(function(){
        refresh_captcha();
    });
</script>